import { DirectiveBinding, ObjectDirective } from 'vue'
import Clipboard from 'clipboard'

// Inspired by https://github.com/Inndy/vue-clipboard2
if (!Clipboard) {
  throw new Error('you should npm install `clipboard` --save at first ')
}

interface ClipboardElement extends HTMLElement {
  _v_clipboard?: any;
  _v_clipboard_success?: (e: any) => void;
  _v_clipboard_error?: (e: any) => void;
}

const clipboard: ObjectDirective<ClipboardElement> = {
  beforeMount(el: ClipboardElement, binding: DirectiveBinding) {
    if (binding.arg === 'success') {
      el._v_clipboard_success = binding.value
    } else if (binding.arg === 'error') {
      el._v_clipboard_error = binding.value
    } else {
      const clipboard = new Clipboard(el, {
        text: () => binding.value,
        action: () => binding.arg === 'cut' ? 'cut' : 'copy'
      })
      clipboard.on('success', e => {
        const callback = el._v_clipboard_success
        callback && callback(e) // eslint-disable-line
      })
      clipboard.on('error', e => {
        const callback = el._v_clipboard_error
        callback && callback(e) // eslint-disable-line
      })
      el._v_clipboard = clipboard
    }
  },
  
  beforeUpdate(el: ClipboardElement, binding: DirectiveBinding) {
    if (binding.arg === 'success') {
      el._v_clipboard_success = binding.value
    } else if (binding.arg === 'error') {
      el._v_clipboard_error = binding.value
    } else {
      el._v_clipboard.text = () => binding.value
      el._v_clipboard.action = () => binding.arg === 'cut' ? 'cut' : 'copy'
    }
  },
  
  unmounted(el: ClipboardElement, binding: DirectiveBinding) {
    if (binding.arg === 'success') {
      delete el._v_clipboard_success
    } else if (binding.arg === 'error') {
      delete el._v_clipboard_error
    } else {
      el._v_clipboard.destroy()
      delete el._v_clipboard
    }
  }
}

export default clipboard
